package com.itheima.web;

import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/updateUserByIDServlet")
public class UpdateUserByIDServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //拿到所有的数据
        Map<String, String[]> map = request.getParameterMap();

        //创建user对象
        User user = new User();

        //将数据封装到user对象中
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }

        //创建业务类对象调用修改用户信息的方法传入id参数
        boolean result = new UserService().updateUser(user);
        //判断结果
        if(result){
            //成功跳转到updateok页面
            response.sendRedirect("/update_ok.jsp");
        }else{
            //还是跳转会修改页面
            response.getWriter().print("<h1>修改错误!</h1>");
            response.setHeader("refresh","1;url=http://localhost:8080/list.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
